package com.example.backblog.util;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 对象转换工具类
 */
public class TransferUtil {
    /**
     * 转换对象
     * @param origin
     * @param target
     * @param <O>
     * @param <T>
     */
    public static <O,T> void transfer(O origin,T target){

       BeanUtils.copyProperties(origin,target);
    }

    /**
     * 转换对象
     * @param origin
     * @param targetClass
     * @return
     * @param <O>
     * @param <T>
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static <O,T> T transfer(O origin,Class<T> targetClass) throws InstantiationException, IllegalAccessException {

        T target = targetClass.newInstance();
        BeanUtils.copyProperties(origin,target);
        return target;
    }

    /**
     * 转换list
     * @param origin
     * @param targetClass
     * @return
     * @param <O>
     * @param <T>
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static <O,T> List<T> transferList(List<O> origin, Class<T> targetClass) throws InstantiationException, IllegalAccessException {
        List<T> res = new ArrayList<>();
        for (O object : origin) {
            T t = targetClass.newInstance();
            BeanUtils.copyProperties(object,t);
            res.add(t);
        }
        return res;
    }
}
